/**
 * 已办组件(基于ECP3.0前端).
 * 
 * @author xuetianfu
 * @since 2016-06-24
 */
define(
		[ 'ecp.service', 'ecp.component.taskservice','ecp.component.dialog','ecp.pagemessage','ecp.utils','ecp.utils.i18n','bootstrap-select','select2' ],
		function(ecpService, taskService, dialog,message,utils,i18n) {
		
		     /**
		     *用户ID.
		     */
			var USER_ID = ecpService.DataContextUtil.getUserId();
			
			/**
	         * 后端服务对象.
	         */
	        var remoteService = ecpService.RemoteService;
			
			/**
			 * 查询参数(已经做了大小写不区分处理).
			 */
			var QUERY_PARAMS = [ {
				name : "USERID",
				value : USER_ID
			} ];
			
			
			/**
			 * 排序参数(已经做了大小写不区分处理).
			 */
			var ORDER_PARAMS = [ {
				"name" : "TASKCREATETIME",
				"order" : "DESC"
			} ];
			
			/**
			*接口类.
			*/
			var BEAN_ID = "com.ygsoft.ecp.core.web.taskcenter.context.IQueryContext";
			
			//待办列表区域
			var UNTREATED_CONT_AREA;
			//待办翻页控件区域
			var UNTREATED_PAGE_AREA;
			//已办列表区域
			var EXECUTED_CONT_AREA;
			//已办翻页控件区域
			var EXECUTED_PAGE_AREA;

            //任务中心组件容器
            var COMPONENT_CONTAINER;

			/**
			 * 页面初始化入口.
			 *@param container 任务列表容器
			 *@param callbak 任务中心组件初始化后回调函数
			 */
			function init(container,callbak) {
				$.ajax({
                    type: "get",
                    cache:true,
                    url: "/grm/ecp/webcore/components/taskcenter/taskCenter.html",
                    success: function(data) {
                    	COMPONENT_CONTAINER = container;
                        container.html(data);
                         //国际化
                        utils.loadLocale(i18n.wfTodoAndDone,container);
                        utils.domAttrI18n(i18n.wfTodoAndDone,container,"title");
                        utils.domAttrI18n(i18n.wfTodoAndDone,container,"placeholder");
                        if(callbak&&$.isFunction(callbak)){
                           callbak();
                        }
						UNTREATED_CONT_AREA = $('#tab_1 >.djList > ul > li.topBar',COMPONENT_CONTAINER);
						UNTREATED_PAGE_AREA = $('#page1',COMPONENT_CONTAINER);
						EXECUTED_CONT_AREA = $('#tab_2 >.djList > ul > li.topBar',COMPONENT_CONTAINER);
						EXECUTED_PAGE_AREA = $('#page2',COMPONENT_CONTAINER);
						
						var untreatQueryParams = taskService.getQueryParams(false);
						var executedQueryParams = taskService.getQueryParams(true);
						
						var untreatedParams = [untreatQueryParams,ORDER_PARAMS,UNTREATED_CONT_AREA,UNTREATED_PAGE_AREA,setQueryResSize];
						var executedParams = [executedQueryParams,ORDER_PARAMS,EXECUTED_CONT_AREA,EXECUTED_PAGE_AREA,null];
						taskService.setInitParams(untreatedParams,executedParams,COMPONENT_CONTAINER);
						
                        //加载扩展点
						taskService.loadTaskExtList();
						
						$("#unTreatedLoading",container).removeClass("display-hide").addClass("display-show");
						
						//加载待办
						taskService.loadUnTreatedTaskList(untreatQueryParams, ORDER_PARAMS,UNTREATED_CONT_AREA,UNTREATED_PAGE_AREA,setQueryResSize);
						
						//加载已办
						//taskService.loadExecutedTaskList(executedQueryParams,ORDER_PARAMS,EXECUTED_CONT_AREA,EXECUTED_PAGE_AREA,null);
						
						//排序
						activeSortFunc();
						//待办事项排序按钮点击事件
						registClickEvent();
						//查询
						registSearchFunc(container);
						$("#unTreatedLoading",container).removeClass("display-show").addClass("display-hide");
						
						//搜索图标点击事件
						$('#searchBtn',container).off('click').on('click',function(){
							if($('#searchByTaskName',container).val().trim()!=''){
								doQuery()
							}
						});
						
						autoRefresh();
						
						$("#batchReject",container).hide();
						
						//tab页切换,必须刷新当前页数据
						$('a[data-toggle="tab"]',container).on('shown.bs.tab',function(e){
						     doQuery();
						});
						
						var currentWin = parent.window?parent.window:window;
						currentWin.onblur=function(){
							if(autoRefreshTimer){
							    clearInterval(autoRefreshTimer);
							}
						};
						
						currentWin.onfocus=function(){
							if(autoRefreshTimer){
								clearInterval(autoRefreshTimer);
							}
							autoRefresh();
						};
                    }
                });
			}
			
			/**
			*cookie中任务个数.
			*/
			var wfCounter = $.cookie("_ERWF");
			
			/**
			*自动刷新timer.
			*/
			var autoRefreshTimer;
			
			/**
			 * 上次cookie中工作项
			 */
			var lastWorkItemCache;
			/**
			*自动刷新.
			*/
			function autoRefresh(){
			   //监听cookie变化，刷新
				autoRefreshTimer = setInterval(function(){
					var cookieCnt = $.cookie("_ERWF");
					//如果数目不等,相等情况下刷新会太频繁,并且如果只是更新单条,不利于其它规则的同步更新
					if (cookieCnt != wfCounter) {
						taskService.refreshPage();
						wfCounter = cookieCnt;
					}
				},500);
			}
			
			/**
			*设置查询结果条数总计.
			*/
			function setQueryResSize(){
			   taskService.setTodoCount(taskService.getQueryResSize());
			}

			/**
			 * 当前是否待办箱.
			 */
			function isUnTreated() {
				return $("ul.nav-tabs > li",COMPONENT_CONTAINER).index($("ul.nav-tabs > li.active",COMPONENT_CONTAINER)) == 0;
			}

			/**
			 * 激活排序功能.
			 */
			function activeSortFunc() {
				// 排序按钮切换上下箭头点击事件
				$("#tab_1 > div.djList >ul > li.topBar,#tab_2 > div.djList >ul > li.topBar",COMPONENT_CONTAINER).on(
						'click',
						'.btn_sort',
						function() {
							var idx = $(this).parent().find(".btn_sort").index($(this));
							if(idx==3){
							   var isExecuted = !isUnTreated();
							   if(isExecuted){
							   	  ORDER_PARAMS[0].name = taskService.taskConst.ORDER_FIELDS[5];
							   }else{
							   	  ORDER_PARAMS[0].name = taskService.taskConst.ORDER_FIELDS[idx];
							   }
							}else{
								if(isExecuted){
									ORDER_PARAMS[0].name = taskService.taskConst.ORDER_FIELDS[6];
								}else{
									ORDER_PARAMS[0].name = taskService.taskConst.ORDER_FIELDS[idx];
								}
							}
							if ($(this).hasClass("active")) {
								var downClass = "long-arrow-down";
								var upClass = "long-arrow-up";
								var child = $(this).children("i.icon_sm");
								if (child.hasClass(downClass)) {
									var arrow = $(this).children("i.long-arrow-down");
									arrow.removeClass(downClass).addClass(upClass);
									ORDER_PARAMS[0].order = 'ASC';
								} else {
									if (child.hasClass(upClass)) {
										var arrow = $(this).children("i.long-arrow-up");
										arrow.removeClass(upClass).addClass(downClass);
										ORDER_PARAMS[0].order = 'DESC';
									} else {
										return;
									}
								}
							} else {
								ORDER_PARAMS[0].order = 'ASC';
								var arrow = $(this).children("i.long-arrow-down");
								var downClass = "long-arrow-down";
								var upClass = "long-arrow-up";
								arrow.removeClass(downClass).addClass(upClass);
								$(".tab-pane.active .djList .topBar .btn_sort",COMPONENT_CONTAINER).removeClass("active");
								$(this).addClass("active");
							}
							doQuery();
				});
			}
			
			
			
			/*
			*从原查询数组中移除元素.
			*@param params 旧的元素
			*@param removeParm 移除的元素
			*/
			function removeParam(params,removeParam){
			    $.each(params,function(idx,obj){
				       if(obj.name==removeParam.name){
				           params.splice(idx,1);
				           return false;
				       }
				});
			}

			/*
			*是否由搜索框发起的搜索.
			*/
            var isQueryTriggerBySearch = false;

			/**
			 * 注册查询功能.
			 *@param container 任务容器
			 */
			function registSearchFunc(container) {
				var clearTextBtn = $("#clearTextBtn",COMPONENT_CONTAINER);
				clearTextBtn.removeClass("btnClear");
				$("#searchByTaskName",COMPONENT_CONTAINER).on('keyup',function(event) {
					var $me = $(this);
					var val = $me.val();
					if(clearTextBtn.hasClass("hide")){
						if(val != ""){
							clearTextBtn.fadeIn("fast"); // 显示清除按钮
							clearTextBtn.removeClass("hide").addClass("btnClear"); // 去除隐藏标记
						}
					}else if(val === ""){
						clearTextBtn.fadeOut("fast"); // 隐藏清除按钮
						clearTextBtn.addClass("hide").removeClass("btnClear"); // 添加隐藏标记
					}
					isQueryTriggerBySearch = true;
				}).on('keydown',function(event){
				   if(event.keyCode==13){
				        //解决回车会打开门户左侧搜索框,F1151028
				        event.preventDefault();
				        var contentObj;
				        if(isUnTreated()){
				        	contentObj = UNTREATED_CONT_AREA;
				        }else{
				        	contentObj = EXECUTED_CONT_AREA;
				        }
				        doQuery();
				   }
				});
			}
			
			/**
			*查询.
			*/
			function doQuery(){
			        //如果上一次查询还没有结束,不允许发起新的查询
                    if($(".freshPage",COMPONENT_CONTAINER).attr('disabled')){
                      	return;
                    }
					if (this.timeoutID) {
                        clearTimeout(this.timeoutID);
                    }
                    this.timeoutID = setTimeout(function () {
                    	doQueryByTaskCategory(!isUnTreated());
						//无论是切换一级维度,二级维度,搜索框查询都会走这里
						taskService.isQueryChanged(true);
                    }, 1000);
			}
			
			/**
			*查询.
			*/
			function doQueryByTaskCategory(isExecuted){
					var params = taskService.getQueryParams(isExecuted);
				    if(isExecuted){
						taskService.loadExecutedTaskList(params,ORDER_PARAMS,EXECUTED_CONT_AREA,EXECUTED_PAGE_AREA);
					}else{
						taskService.loadUnTreatedTaskList(params, ORDER_PARAMS,UNTREATED_CONT_AREA,UNTREATED_PAGE_AREA,setQueryResSize);
					}
			}

			
			/**
			 * 待办事项排序按钮点击事件.
			 */
			function registClickEvent() {
				//点击待办、已办列表title三角，收缩、展开列表
				COMPONENT_CONTAINER.find(".djList").off("click").on('click','ul>li.taskItem>ul.listGroupTitle>li>a.lgt_collapse',function(){
						var arrow = $(this);
						var i = $(this).children(".fa");
						var listGroupContent = $(this).closest(".listGroupTitle").next(".listGroupContent");
						if (arrow.hasClass("open")) {
							arrow.removeClass("open");
							i.removeClass("fa-caret-up").addClass("fa-caret-down");
							listGroupContent.slideUp("fast");
						} else {
							arrow.addClass("open");
							i.removeClass("fa-caret-down").addClass("fa-caret-up");
							listGroupContent.slideDown("fast");
						}
				})
				//流程进行中,流程已完结
				$("#sx_flowBtnGroup > button",COMPONENT_CONTAINER).on('click',function(){
							if ($(this).hasClass("active")) {
								return;
							}
							$("#sx_flowBtnGroup > button",COMPONENT_CONTAINER).removeClass("btn-primary").removeClass("active");
							$(this).addClass("btn-primary").addClass("active");
							doQuery();
				});
				//我处理,我发起
				$("#sx_flowBtnGroup1 > button",COMPONENT_CONTAINER).on('click',function(){
							if ($(this).hasClass("active")) {
							    return;
							}
							$("#sx_flowBtnGroup1 > button",COMPONENT_CONTAINER).removeClass("btn-primary").removeClass("active");
							$(this).addClass("btn-primary").addClass("active");
							doQuery();
				});
				// 初始化搜索框（清除搜索框中文本） 和 搜索框中的清除按钮（隐藏按钮）
				var clearTextBtn = $("#clearTextBtn",COMPONENT_CONTAINER);
				clearTextBtn.parent(".input-icon").find("input").val("");
				clearTextBtn.hide().addClass("hide");
				//查询条件清空
				clearTextBtn.off("click").on('click', function(){
					$("#searchByTaskName",COMPONENT_CONTAINER).val('');
					var $me = $(this);
					$me.parent(".input-icon").find("input").focus();
					$me.fadeOut("fast"); // 隐藏清除按钮
					$me.addClass("hide"); // 添加隐藏标记
					$me.addClass("hide").removeClass("btnClear");
					doQuery();
				});
				
				//刷新页面
				COMPONENT_CONTAINER.find(".djList").on("click",".freshPage", function(){
				    doQuery();
				    $(this).blur();
				});
				
				//鼠标覆盖事件,显示或隐藏附件信息表格
				var dataView = COMPONENT_CONTAINER.children("[class!='topBar'][class!='bottomBar']");
				dataView.on("mouseleave", "div[tag='wfAttachment']", function(e){
					var el = $(this);
					if (!el.attr("preview")) {
						$(this).addClass("display-hide");
					}
				}).on("mouseenter", "div[tag='wfAttachment']", function(e){
					$(this).removeClass("display-hide");
				});
				
				//回退modal窗口位置重置
				$("body").on('shown.bs.modal','div[id^=wfTodoAuditWin]', function (e) {
				        var marginTop = $(this).find(".modal-dialog").css("margin-top").replace("px","");
					    $(this).css({
					        'top':$(window).height()/2-$(this).find(".modal-dialog").height()/2-marginTop
					    }); 
				}); 
			}
			
			
			/**
			*返回待办总数.
			*/
			function getUntreatedSize(){
			   remoteService.doPostAsync(BEAN_ID, 'getUntreatedTaskSizeByCondition',
                [QUERY_PARAMS], function(resp) {
                    if (resp.isSuccess()) {
                         return resp.data;
                    }
                    if (resp.isError()) {
                       return 0;
                    }
               });     
			}
			
			return {
				render: function(container){
					init(container);
				},
				taskConst:taskService.taskConst,
				refreshPage:taskService.refreshPage,
				getUntreatedSize:getUntreatedSize
			}
});
